﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml.Linq;
using Microsoft.SqlServer.Server;
using System.Xml;
using System.Threading;
using CustomerEmailer.Common;
using System.Net.Mail;
using System.IO;
using System.Net;
using Finisar.SQLite;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;

namespace CustomerEmailer
{
    public delegate void UpdateClientEmailSent(Exception excpetion, string usrEmail);

    public partial class Main : Form
    {
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;

        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd,
                         int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        EmailService emailService;
        BackgroundWorker bwHistory;
        public List<string> AttachedFiles
        {
            get;
            set;
        }
        public const string XML_FILE_LOCATION = "customers.xml";
        public const string REPLACE_STRING = "{שם}";
        private int sendToCount;
        object lockCounters = new object();
       // bool updateHistory = false;
        BackgroundWorker worker;
        BackgroundWorker cSyncworker;
        int count; //for history
        int nTimesDisconnect=0;
        long toRevision;
        private bool sending = false;
        List<Customer> customers, customersNotSent;

        [Serializable()]
        class historyUpdateStruct
        {
            public string name;
            public string email;
            public string subject;
            public string html;
            public string time;
            public int sendtocount;
            public string username;
        }

        List<historyUpdateStruct> historyUpdates=new List<historyUpdateStruct>();

        int SendToCount
        {
            get
            {
                return sendToCount;
            }
            set
            {
                lock (lockCounters)
                {
                    sendToCount = value;
                }
            }
        }

        private int sendToGoal;
        int SendToGoal
        {
            get
            {
                return sendToGoal;
            }
            set
            {
                lock (lockCounters)
                {
                    sendToGoal = value;
                }
            }
        }

        private int sendAllCount;
        int SendAllCount
        {
            get
            {
                return sendAllCount;
            }
            set
            {
                lock (lockCounters)
                {
                    sendAllCount = value;
                }
            }
        }

        private int totalNotSentTo;
        int TotalNotSentTo 
        {
            get
            {
                return totalNotSentTo;
            }
            set
            {
                lock (lockCounters)
                {
                    totalNotSentTo = value;
                }
            }
        }


        public Main()
        {
            InitializeComponent();
        }
        
        private Control focusedTextbox = null;
        private void Main_Load(object sender, EventArgs e)
        {
            htmlEditorControl.Enter += textBox_Enter;
            tbSubject.Enter += textBox_Enter;

            contactsTreeView.treeView1.AllowDrop = false;
            contactsTreeView.treeView1.CheckBoxes = true;
            contactsTreeView.treeView2.AllowDrop = false;
            contactsTreeView.treeView2.CheckBoxes = true;
            emailService=new EmailService((EmailService.EmailServiceName)int.Parse(Utils.GetSetting("ServiceName")),
               Utils.GetSetting("Email"), Utils.GetSetting("Password"));

            AttachedFiles = new List<string>();
            htmlEditorControl.Cursor = System.Windows.Forms.Cursors.Arrow; 
            contactsTreeView.treeView1.AfterSelect+= new TreeViewEventHandler(treeView1_AfterSelect);
            contactsTreeView.treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(TreeNodeDbClicked);
            contactsTreeView.treeView2.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect);
            contactsTreeView.treeView2.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(TreeNodeDbClicked);

            htmlEditorControl.BodyHtml = Utils.GetSetting("Signature");
            contactsTreeView.treeView1.Size = new Size(328, 429);
            contactsTreeView.treeView2.Size = new Size(328, 429);
            contactsTreeView.Size = new Size(328, 429);
            contactsTreeView.InitalizeTreeNode(XML_FILE_LOCATION);
            SyncTimer_Tick(null, null);
            if (File.Exists(Utils.GetMainFolderLocation("contactsdata.bin")))
            {
                DialogResult dialogResult = MessageBox.Show("האם ברצונך לטעון נתונים משליחה קודמת?", "BizMail", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    getCheckedContacts();
                    TreeNode node = null;
                    foreach (Customer x in customers)
                    {
                        Utils.SilentlyFindNodeInHierarchyByPath(contactsTreeView.treeView1.Nodes, x.Fullpath, ref node, "Email");
                        if (node!=null)
                            node.Parent.Checked = true;
                    }
                }
            }
            getHistory();
        }

        void TreeNodeDbClicked(object sender, System.EventArgs e)
        {
            if (contactsTreeView.selectedTreeView.SelectedNode != null)
            {
                if (contactsTreeView.selectedTreeView.SelectedNode.ImageKey == "Customers")
                {
                    bool nChecked=true;
                    contactsTreeView.nothingChecked(contactsTreeView.selectedTreeView.Nodes[0],ref nChecked);
                    if (nChecked)
                    {
                        if (checkServerAvailability("contacts"))
                        {
                            customersNotSent = contactsTreeView.GetCheckedCustomers();
                            storeCheckedContacts();
                            Contacts c = new Contacts(this);
                            c.FormClosed += new FormClosedEventHandler(c_FormClosed);
                            c.ShowDialog();
                        }
                        else
                        {
                            MessageBox.Show("לא ניתן לבצע עידכונים ברגע זה כיוון שמשתמש אחר מבצע עדכונים. נסה שוב מאוחר יותר");
                        }
                    }
                }
            }
        }

        void textBox_Enter(object sender, EventArgs e)
        {
            focusedTextbox = (Control)sender;
        }

        private void btnSendEmail_Click(object sender, EventArgs e)
        {
            if (btnSendEmail.Text == "שלח")
            {
                if (Utils.GetSetting("Email") == string.Empty)
                {
                    MessageBox.Show("קובץ ההגדרות שהזנת אינו תקין");
                    return;
                }
                //Update MailService Procedure before sending
                emailService.updateMailService((EmailService.EmailServiceName)int.Parse(Utils.GetSetting("ServiceName")),
                    Utils.GetSetting("Email"), Utils.GetSetting("Password"));

                lblFailedMails.Text = "0";
                lblSuccsfulSentMails.Text = "0";
                lblSumMails.Text = "0";
                lblLastSentTo.Text = string.Empty;

                customers = contactsTreeView.GetCheckedCustomers();
                customers.Sort();
                SendToGoal = customers.Count;
                lblSumMails.Text = sendToGoal.ToString();
                lblStatus.Text = "שולח...";
                btnSendEmail.Text = "בטל שליחה";
                var title = tbSubject.Text;
                var html = htmlEditorControl.BodyHtml;

                worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler(SendEmails);

                var parameters = new object[] { customers, html };
                worker.RunWorkerAsync(parameters);
                worker.WorkerSupportsCancellation = true;
                sending = true;
            }
            else
            {
                if (btnSendEmail.Text == "בטל שליחה")
                {
                    worker.CancelAsync();
                    SendAllCount = 0;
                    SendToCount = 0;
                    TotalNotSentTo = 0;
                    SendToGoal = 0;
                    lblStatus.Text = string.Empty;
                    btnSendEmail.Text = "אנא המתן";
                    btnSendEmail.Enabled = false;
                    lblWorking.Text = "";
                }
            }
        }

        private void SendEmails(object sender, DoWorkEventArgs e)
        {
            //SyncTimer.Stop();
            //SyncTimer.Enabled = false;
            var parameters = (e.Argument as object[]);
            if (parameters == null || parameters.Length<2)
                return;
            customers= parameters[0] as List<Customer>;
            customersNotSent = new List<Customer>();
            customersNotSent.AddRange(customers);
            storeCheckedContacts();
            string html = parameters[1].ToString();
            Logger logger = new Logger();
            MailMessage message;
            int i = 0;
            string mailTime = DateTime.Now.Ticks.ToString();
            bool success = false;
            int timewait=Int32.Parse(Utils.GetSetting("WaitBetweenSendings"));
            foreach (var customer in customers)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                string replacedTitle = tbSubject.Text.Replace(REPLACE_STRING, customer.Name.Replace("''", "\""));
                string replacedHtml = html.Replace(REPLACE_STRING, customer.Name.Replace("''", "\""));
                message = new MailMessage(new MailAddress(Utils.GetSetting("Email"), Utils.GetSetting("UserName")), new MailAddress(customer.Email));
                message.Body = replacedHtml;
                message.IsBodyHtml = true;
                message.Subject = replacedTitle;

                foreach (string attach in AttachedFiles)
                {
                    message.Attachments.Add(new Attachment(@attach));
                }
                success = emailService.sendMessage(message);
                if (success)
                {
                    int currentSuccesfulMails = int.Parse(lblSuccsfulSentMails.Text);
                    this.Invoke(new MethodInvoker(delegate { lblSuccsfulSentMails.Text = (currentSuccesfulMails + 1).ToString(); }));
                    historyUpdateStruct x = new historyUpdateStruct();
                    x.name = customer.Name;
                    x.email = customer.Email;
                    x.subject = tbSubject.Text;
                    x.html = html;
                    x.sendtocount = SendToCount;
                    x.time = mailTime;
                    x.username = Utils.GetSetting("UserName");
                    historyUpdates.Add(x);
                    SendToCount++;
                }
                else
                {
                    TotalNotSentTo++;
                    logger.Log(customer.Name, customer.Email, replacedTitle, replacedHtml, AttachedFiles.Count);
                    this.Invoke(new MethodInvoker(delegate { lblFailedMails.Text = (TotalNotSentTo).ToString(); }));
                }
                if (customersNotSent.Count>0)
                 customersNotSent.RemoveAt(0);
                storeCheckedContacts();
                SendAllCount++;
                this.Invoke(new MethodInvoker(delegate { lblStatus.Text = "מחכה..."; }));
                Thread.Sleep(timewait);
                this.Invoke(new MethodInvoker(delegate { lblStatus.Text = "שולח..."; }));
            }

            this.Invoke(new MethodInvoker(delegate { lblStatus.Text = string.Empty; }));

            if (TotalNotSentTo > 0)
            {

                this.Invoke(new MethodInvoker(delegate { lblWorking.Text = "השליחה הסתיימה, לא בהצלחה"; }));
                MessageBox.Show("שים לב, לא כולם קיבלו את ההודעה", "השליחה הסתיימה", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                message = new MailMessage(new MailAddress(Utils.GetSetting("Email"), Utils.GetSetting("UserName")), new MailAddress(Utils.GetSetting("Email")));
                message.Body = Logger.readLog();
                message.IsBodyHtml = true;
                message.Subject = "מיילים שלא התקבלו";
                emailService.sendMessage(message);
            }
            else
            {
                this.Invoke(new MethodInvoker(delegate { lblWorking.Text = "השליחה הסתיימה"; }));
                MessageBox.Show("כל ההודעות נשלחו בהצלחה");
            }

            SendAllCount = 0;
            SendToCount = 0;
            TotalNotSentTo = 0;
            SendToGoal = 0;

            sending = false;
            this.Invoke(new MethodInvoker(delegate { btnSendEmail.Enabled = true; }));
            this.Invoke(new MethodInvoker(delegate { btnSendEmail.Text = "שלח"; }));
            this.Invoke(new MethodInvoker(delegate { lblWorking.Text = ""; }));
           // SyncTimer.Start();
            //SyncTimer.Enabled = true;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            htmlEditorControl.ResetText();
            tbSubject.Text = string.Empty;
            lblStatus.Text = string.Empty;

            lblFailedMails.Text = "0";
            lblSuccsfulSentMails.Text = "0";
            lblSumMails.Text = "0";
            lblLastSentTo.Text = string.Empty;

            AttachedFiles.Clear();
            label5.Text = AttachedFiles.Count.ToString();
            htmlEditorControl.BodyHtml = Utils.GetSetting("Signature");
            contactsTreeView.InitalizeTreeNode(XML_FILE_LOCATION);
           // if (contactsTreeView.selectedTreeView.Nodes[0] != null)
            //    contactsTreeView.selectedTreeView.Nodes[0].Checked = false;
        }

        private void btnAddUser_Click(object sender, EventArgs e)
        {
            if (focusedTextbox != null)
            {
                if (focusedTextbox.GetType() == htmlEditorControl.GetType())
                    htmlEditorControl.SelectedText = REPLACE_STRING;
                else
                    focusedTextbox.Text = string.Format("{0} {1}", focusedTextbox.Text, REPLACE_STRING);
            }
        }

        private void btnEditContacts_Click(object sender, EventArgs e)
        {
            if (checkServerAvailability("contacts"))
            {
                customersNotSent = contactsTreeView.GetCheckedCustomers();
                storeCheckedContacts();
                Contacts c = new Contacts(this);
                c.FormClosed += new FormClosedEventHandler(c_FormClosed);
                c.ShowDialog();
            }
            else
            {
                MessageBox.Show("לא ניתן לבצע עידכונים ברגע זה כיוון שמשתמש אחר מבצע עדכונים. נסה שוב מאוחר יותר");
            }
        }
    
        void c_FormClosed(object sender, FormClosedEventArgs e)
        {
            textBox1.Clear();
          //  x.Log(Utils.GetSetting("ErrorFile"), "clearing ");
            contactsTreeView.InitalizeTreeNode(XML_FILE_LOCATION);
            getCheckedContacts();
            TreeNode node = null;
            foreach (Customer x in customers)
            {
                Utils.SilentlyFindNodeInHierarchyByPath(contactsTreeView.treeView1.Nodes, x.Fullpath, ref node, "Email");
                if (node != null)
                    node.Parent.Checked = true;
            }
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?cancelContactsAvailable");
            request.Method = "GET";
            request.ContentType = "text/plain";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            response.Close();
            SyncTimer.Start();
            SyncTimer.Enabled = true;
        }

        private void btnAddFiles_Click(object sender, EventArgs e)
        {
            AttachFile attachForm = new AttachFile(this);
            attachForm.FormClosed += new FormClosedEventHandler(attachForm_FormClosed);
            attachForm.ShowDialog();
        }

        void attachForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            label5.Text = AttachedFiles.Count.ToString();
        }

        private void btnSettings_Click(object sender, EventArgs e)
        {
            Settings settings = new Settings(this);
            settings.ShowDialog();
        }

        private void SBLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", " http://www.socialbiz.co.il");
        }

        private void עריכתאנשיקשרToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (checkServerAvailability("contacts"))
            {
                customersNotSent = contactsTreeView.GetCheckedCustomers();
                storeCheckedContacts();
                Contacts c = new Contacts(this);
                c.FormClosed += new FormClosedEventHandler(c_FormClosed);
                c.ShowDialog();
            }
            else
            {
                MessageBox.Show("לא ניתן לבצע עידכונים ברגע זה כיוון שמשתמש אחר מבצע עדכונים. נסה שוב מאוחר יותר");
            }
        }

        private void הגדרותToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            Settings settings = new Settings(this);
            settings.ShowDialog();
        }

        private void אודותToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", " http://www.socialbiz.co.il");
        }

        void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = contactsTreeView.selectedTreeView.SelectedNode;
            if (node.ImageKey=="Customers")
            {
                string[] array1=node.Tag.ToString().Split('#');
                lblDetails.Text = string.Format("{0}\n {1} \n נייד: " + "{2} \n משרד: "  + "{3}\n כתובת: "+"{4}", node.Text, node.ToolTipText, array1[0], array1[1],array1[2]);
                List<TreeNode> node_list = new List<TreeNode>();
                Utils.getEquivalentNodes(contactsTreeView.treeView1.Nodes, ref node_list, node);
                lvGroups.Clear();
                foreach (TreeNode node1 in node_list)
                {
                    lvGroups.Items.Add(new ListViewItem(node1.Parent.Text));
                }
            }
            else if (node.ImageKey=="Email"){
                string[] array1 = node.Parent.Tag.ToString().Split('#');
                lblDetails.Text = string.Format("{0}\n {1} \n נייד: " + "{2} \n משרד: " + "{3}\n כתובת: "+"{4}", node.Parent.Text, node.Parent.ToolTipText, array1[0], array1[1], array1[2]);
                lvGroups.Clear();
            }
            else{
                lblDetails.Text = "";
                lvGroups.Clear();
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Length >= 3)
            {
                contactsTreeView.treeView2.Nodes.Clear();
                contactsTreeView.selectedTreeView = contactsTreeView.treeView2;
                Utils.FindNodeInHierarchy(contactsTreeView.treeView1.Nodes,  contactsTreeView.treeView2, textBox1.Text, contactsTreeView.treeView1);
                contactsTreeView.treeView2.Visible = true;
                contactsTreeView.treeView1.Visible = false;
            }
            if (textBox1.Text == "")
            {
                contactsTreeView.selectedTreeView = contactsTreeView.treeView1;
                contactsTreeView.treeView1.Visible = true;
                contactsTreeView.treeView2.Visible = false;
            }
        }

        private void SyncTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                toRevision = 0;
                lbSync.Text = "בודק עדכונים...";
                if (!sending && shouldSync(ref toRevision) && !Utils.synchronzingContacts)
                {
                    Utils.synchronzingContacts = true;
                    lbSync.Text = "מתעדכן...";
                    progressBar2.Visible = true;
                    progressBar2.Maximum = 100;
                    cSyncworker = new BackgroundWorker();
                    cSyncworker.WorkerSupportsCancellation = true;
                    cSyncworker.WorkerReportsProgress = true;
                    cSyncworker.ProgressChanged += new ProgressChangedEventHandler(cSyncworker_ProgressChanged);
                    cSyncworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(cSyncworker_RunWorkerCompleted);
                    cSyncworker.DoWork += new DoWorkEventHandler(syncServer);
                    cSyncworker.RunWorkerAsync();
                    //syncServer();
                    //contactsTreeView.InitalizeTreeNode(XML_FILE_LOCATION);
                }
                lbSync.Text = "מחובר";
                if (historyUpdates.Count > 0 && !sending && !Utils.updatingHistory)
                {
                    if (checkServerAvailability("history"))
                    {
                        List<historyUpdateStruct> tempHhistoryUpdates = new List<historyUpdateStruct>();
                        count = historyUpdates.Count;
                        for (int index = 0; index < count; index++)
                        {
                            tempHhistoryUpdates.Add(historyUpdates[index]);
                        }
                        int i = 0;
                        foreach (historyUpdateStruct update in tempHhistoryUpdates)
                        {
                            saveMailHistory(update.name, update.email, update.subject, update.html, update.sendtocount, update.time, update.username);
                            i++;
                        }
                        Utils.updatingHistory = true;
                        progressBar1.Visible = true;
                        progressBar1.Maximum = 100;
                        bwHistory = new BackgroundWorker();
                        bwHistory.WorkerSupportsCancellation = true;
                        bwHistory.WorkerReportsProgress = true;
                        bwHistory.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
                        bwHistory.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                        bwHistory.DoWork += new DoWorkEventHandler(updateHistoryServer);
                        bwHistory.RunWorkerAsync();
                    }
                }
            }
            catch (System.UnauthorizedAccessException notAdminException)
            {
                this.Invoke(new MethodInvoker(delegate { MessageBox.Show("אנא הרץ את האפליקציה כמנהל"); }));

            }
            catch (IOException exception)
            {
                this.Invoke(new MethodInvoker(delegate { MessageBox.Show("הקובץ כרגע בשימוש"); }));
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ConnectFailure || ex.Status == WebExceptionStatus.Timeout)
                {
                    if (nTimesDisconnect == 30)
                    {
                        nTimesDisconnect = 0;
                        lbSync.Text = "לא ניתן להתחבר לשרת. אנא שנה הגדרות שרת.";
                        SyncTimer.Enabled = false;
                        SyncTimer.Stop();
                    }
                    else
                    {
                        nTimesDisconnect++;
                    }
                }
                else
                {
                    lbSync.Text = "מחובר";
                }
            }
        }

        private bool shouldSync(ref long toRevision)
        {
            //string myhash=Utils.getXMLHash(XML_FILE_LOCATION);
            //Initialization, we use localhost, change if applicable
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?shouldSyncContacts");
            //This time, our method is GET.
            WebReq.Timeout = 1000;
            WebReq.Method = "GET";
            //From here on, it's all the same as above.
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
            //Let's show some information about the response

            //Now, we read the response (the string), and output it.

            Stream Answer = WebResp.GetResponseStream();
            StreamReader _Answer = new StreamReader(Answer);
            toRevision=long.Parse(_Answer.ReadToEnd());
            Answer.Close();
            WebResp.Close();
            return (toRevision!=Utils.contactsRevision);
        }

        private void syncServer(object sender, EventArgs e)
        {
            try
            {
            BackgroundWorker localworker = sender as BackgroundWorker;
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?syncContacts");
            WebReq.Method = "GET";
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
            Stream Answer = WebResp.GetResponseStream();
            string path = Utils.GetXmlFileLocation(XML_FILE_LOCATION);
                FileStream myFile = new FileStream(path,FileMode.Create,FileAccess.Write,FileShare.None);
                byte[] buffServer = new byte[1024];
                int readbytes = 1;
                long totalreadbytes = 0;
                while (readbytes > 0)
                {
                    readbytes = Answer.Read(buffServer, 0, buffServer.Length);
                    totalreadbytes += readbytes;
                    localworker.ReportProgress((int)(totalreadbytes * 100 / WebResp.ContentLength));
                    if (readbytes > 0)
                        myFile.Write(buffServer, 0, readbytes);
                }
                myFile.Close();
                Answer.Close();
                WebResp.Close();
            }
            catch (System.UnauthorizedAccessException notAdminException)
            {
                this.Invoke(new MethodInvoker(delegate { MessageBox.Show("אנא הרץ את האפליקציה כמנהל"); }));
                
            }
            catch (IOException exception)
            {
                this.Invoke(new MethodInvoker(delegate { MessageBox.Show("הקובץ כרגע בשימוש"); }));
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ConnectFailure || ex.Status == WebExceptionStatus.Timeout)
                {
                    if (nTimesDisconnect == 30)
                    {
                        nTimesDisconnect = 0;
                        lbSync.Text = "לא ניתן להתחבר לשרת. אנא שנה הגדרות שרת.";
                        SyncTimer.Enabled = false;
                        SyncTimer.Stop();
                    }
                    else
                    {
                        nTimesDisconnect++;
                    }
                }
                else
                {
                    lbSync.Text = "מחובר";
                }
            }
        }

        private void cSyncworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
            }

            else if (!(e.Error == null))
            {
                throw e.Error;
            }

            else
            {
                progressBar2.Value = 100;
                progressBar2.Visible = false;                
                Utils.contactsRevision = toRevision;
                Utils.synchronzingContacts = false;
                lbSync2.Text = "עודכן לאחרונה ב " + DateTime.Now.ToString();
            }
        }

        private void cSyncworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar2.Value = (e.ProgressPercentage);
        }



        private bool checkServerAvailability(string type)
        {
            HttpWebRequest WebReq = null;
            if (type == "contacts")
                WebReq = (HttpWebRequest)WebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?contactsAvailable");
            else if (type == "history")
                WebReq = (HttpWebRequest)WebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?historyAvailable");
            WebReq.Method = "GET";
            WebReq.Timeout = 2000;
            HttpWebResponse WebResp=null;
            try
            {
                WebResp = (HttpWebResponse)WebReq.GetResponse();
            }
            catch (WebException e) { if (e.Status != WebExceptionStatus.ConnectFailure && e.Status != WebExceptionStatus.Timeout)
                return false; }
            if (WebResp == null) return false;
                Stream Answer = WebResp.GetResponseStream();
                FileStream myFile=null;
                if (type == "history")
                    myFile= new FileStream(Utils.GetMainFolderLocation("History.db"),FileMode.Create,FileAccess.Write,FileShare.None);
                else if (type == "contacts")
                    myFile = new FileStream(Utils.GetXmlFileLocation(XML_FILE_LOCATION), FileMode.Create, FileAccess.Write, FileShare.None);
                byte[] buffServer = new byte[1024];
                int readbytes=1;
                long totalreadbytes = 0;
                progressBar1.Visible = true;
                progressBar1.Maximum = 100;
                try
                {
                    while (readbytes > 0)
                    {
                        readbytes = Answer.Read(buffServer, 0, buffServer.Length);
                        totalreadbytes += readbytes;
                        progressBar1.Value = (int)(totalreadbytes * 100 / WebResp.ContentLength);
                        if (readbytes>0)
                            myFile.Write(buffServer, 0, readbytes);
                    }
                    progressBar1.Value = 100;
                    progressBar1.Visible = false;
                    myFile.Close();
                    Answer.Close();
                }
                catch (System.UnauthorizedAccessException notAdminException)
                {
                    MessageBox.Show("אנא הרץ את האפליקציה כמנהל");
                }
                catch (IOException exception)
                {
                    MessageBox.Show("הקובץ כרגע בשימוש");
                }
            string returnString = WebResp.StatusCode.ToString();
            WebResp.Close();
            return (returnString == "OK");     

        }

        private void saveMailHistory(string tocontactName,string toContactEmail, string headline, string html, int nTimes, string mailTime, string sentFrom)
        {
            SQLiteConnection sql_con = new SQLiteConnection("Data Source=History.db;Version=3;New=False;Compress=True;");
            SQLiteCommand sql_cmd;
            string txtQuery;

            sql_con.Open();

            if (nTimes == 0)
            {
                txtQuery = "insert into mails(sentFrom,headline,desc,date) values('" + sentFrom + "','" + headline.Replace("'", "''") + "','" + html.Replace("'", "''") + "','" + mailTime + "')";
                sql_cmd = sql_con.CreateCommand();
                sql_cmd.CommandText = txtQuery;
                sql_cmd.ExecuteNonQuery();
            }
          
            txtQuery = "insert into contacts_mails(email,contactname,maildate) values('" + toContactEmail + "','" + tocontactName + "','" + mailTime + "')";
            sql_cmd = sql_con.CreateCommand();
            sql_cmd.CommandText = txtQuery;
            sql_cmd.ExecuteNonQuery();

            sql_con.Close();
        }

        private void היסטוריהToolStripMenuItem_Click(object sender, EventArgs e)
        {
                History history = new History();
                history.ShowDialog();
        }

        private void SaveSetting(string settingKey, string settingValue)
        {
            string fileLocation = Utils.GetXmlFileLocation("settings.xml");
            XDocument xDoc = XDocument.Load(fileLocation);
            xDoc.Element("configuration").Element(settingKey).Value = settingValue;
            xDoc.Save(fileLocation);
        }

        private void btnSign_Click(object sender, EventArgs e)
        {
            SaveSetting("Signature", htmlEditorControl.BodyHtml);
        }

        private void Main_Paint(object sender, PaintEventArgs e)
        {
            this.Region = new System.Drawing.Region(Utils.drawRoundedRect(0, 0, 30, this.Height, this.Width));
            Utils.drawBorder(0, 0, 30, this.Height, this.Width, e);
        }

        private void Main_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            storeHistory();
            this.Close();
        }

        private void storeHistory()
        {
            using (Stream stream = File.Open(Utils.GetMainFolderLocation("historydata.bin"), FileMode.Create))
                {
                    BinaryFormatter bin = new BinaryFormatter();
                    bin.Serialize(stream, historyUpdates);
                    stream.Close();
                }
        }

        private void getHistory()
        {
                using (Stream stream = File.Open(Utils.GetMainFolderLocation("historydata.bin"), FileMode.Open))
                {
                    BinaryFormatter bin = new BinaryFormatter();

                    historyUpdates = (List<historyUpdateStruct>)bin.Deserialize(stream);
                    stream.Close();
                }
        }

        private void storeCheckedContacts()
        {
            using (Stream stream = File.Open(Utils.GetMainFolderLocation("contactsdata.bin"), FileMode.Create))
                {
                    BinaryFormatter bin = new BinaryFormatter();
                    bin.Serialize(stream, customersNotSent);
                    stream.Close();
                }
        }

        private void getCheckedContacts()
        {
            using (Stream stream = File.Open(Utils.GetMainFolderLocation("contactsdata.bin"), FileMode.Open))
                {
                    BinaryFormatter bin = new BinaryFormatter();

                    customers = (List<Customer>)bin.Deserialize(stream);
                    stream.Close();
                }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //throw new Exception();
            this.WindowState = FormWindowState.Minimized;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("IExplore", " http://www.socialbiz.co.il");
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Utils.updatingContacts)
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?cancelContactsAvailable");
                request.Method = "GET";
                request.ContentType = "text/plain";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            if (Utils.updatingHistory)
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?cancelHistoryAvailable");
                request.Method = "GET";
                request.ContentType = "text/plain";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
        }

        private void updateHistoryServer(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker localworker = sender as BackgroundWorker;
                byte[] arr = new byte[1024];
                FileStream file = File.OpenRead(Utils.GetMainFolderLocation("History.db"));
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://" + Utils.GetSetting("ServerIP") + ":8080?updateHistory");
                request.Method = "PUT";
                request.ContentType = "text/plain";
                request.ContentLength = file.Length;
                Stream dataStream = request.GetRequestStream();
                int bytesRead = 1;
                long totalreadbytes = 0;
                while (bytesRead > 0)
                {
                    bytesRead = file.Read(arr, 0, arr.Length);
                    totalreadbytes += bytesRead;
                    localworker.ReportProgress((int)(totalreadbytes * 100 / file.Length));
                    if (bytesRead > 0)
                        dataStream.Write(arr, 0, bytesRead);
                }
                dataStream.Close();
                file.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string returnString = response.StatusCode.ToString();
                response.Close();
                // Perform a time consuming operation and report progress.
                //System.Threading.Thread.Sleep(500);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ConnectFailure || ex.Status == WebExceptionStatus.Timeout)
                {
                    if (nTimesDisconnect == 30)
                    {
                        nTimesDisconnect = 0;
                        lbSync.Text = "לא ניתן להתחבר לשרת. אנא שנה הגדרות שרת.";
                        SyncTimer.Enabled = false;
                        SyncTimer.Stop();
                    }
                    else
                    {
                        nTimesDisconnect++;
                    }
                }
                else
                {
                    lbSync.Text = "מחובר";
                }
            }
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
            }

            else if (!(e.Error == null))
            {
                throw e.Error;
            }

            else
            {
                progressBar1.Value = 100;
                progressBar1.Visible = false;
                if (historyUpdates.Count>=count)
                    historyUpdates.RemoveRange(0, count);
                Utils.updatingHistory = false;
            }
        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = (e.ProgressPercentage);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            contactsTreeView.InitalizeTreeNode(XML_FILE_LOCATION);
        }
    }
}